<template>
  <div>
    <el-page-header :icon="null" title="用户管理">
      <template #content>
        <span class="text-large font-600 mr-3"> 添加用户 </span>
      </template>
    </el-page-header>

    <el-card>
      <el-form ref="userFormRef" :model="userForm" :rules="userFormRules" label-width="80px" class="demo-ruleForm"
        status-icon>
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" />
        </el-form-item>

        <!-- 用户密码 -->
        <el-form-item label="用户密码" prop="password">
          <el-input type="password" autocomplete="off" v-model="userForm.password" />
        </el-form-item>

        <!-- 用户权限 -->
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="select" style="width: 100%;">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 用户简介 -->
        <el-form-item label="简介" prop="introduction">
          <el-input v-model="userForm.introduction" type="textarea" />
        </el-form-item>

        <!-- 用户头像 -->
        <el-form-item label="头像" prop="avatar">
          <el-upload class="avatar-uploader" action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
            :show-file-list="false" :auto-upload="false" :on-change="handleChange">
            <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">更新</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
const router = useRouter()
const userFormRef = ref()
const userForm = reactive({
  username: '',
  gender: 0,// 性别：默认值为0保密
  password: '',
  role: 2, // 权限：1代表管理员 2代表编辑
  introduction: "",
  avatar: '',
  file: null
})

const userFormRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '用户名长度大于3小于10', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入用户密码', trigger: 'blur' },
    { min: 3, max: 10, message: '用户密码长度大于3小于10', trigger: 'blur' }
  ],
  role: [{ required: true, message: '请选择权限', trigger: 'blur' }],
  intoduction: [{ required: true, message: '请输入简介', trigger: 'blur' }],
  avatar: [{ required: true, message: '请上传头像', trigger: 'blur' }]
})

// 定义校色数据
const options = [
  {
    label: '管理员',
    value: 1
  },
  {
    label: '编辑',
    value: 2
  }
]

// 选择完图片之后回调（每次选择完图片之后的回调）
const handleChange = (file) => {
  // 回显参数
  userForm.avatar = URL.createObjectURL(file.raw)
  // 存储到form表单，提交到后端
  userForm.file = file.raw
}

/**
 * 添加用户提交
 */
const submitForm = () => {
  userFormRef.value.validate((valid) => {
    if (valid) {
      const parmas = new FormData()
      for (let i in userForm) {
        parmas.append(i, userForm[i])
      }
      console.log(parmas)
      // 提交数据到后端
      axios.post('/adminapi/user/addUser', parmas, {
        headers: {
          "Content-Type": "multipart/form-data",
        }
      }).then(res => {
        if (res.data.status !== 0) {
          ElMessage.error('添加用户失败，请重新添加！')
        } else {
          ElMessage.success('添加用户成功！')
          router.push('./UserList')
        }
      })
    }
  })
}
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 30px;
}


::v-deep .avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

::v-deep .avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

::v-deep .el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
}
</style>

